package com.xxxx.core.shiro;

import com.xxxx.core.token.DefaultTokenPorcessor;
import com.xxxx.core.token.ITokenProcessor;
import com.xxxx.core.token.TokenFactory;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.DefaultSessionManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.mgt.DefaultWebSubjectFactory;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.MethodInvokingFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Configuration
public class ShiroConfig {
	@Value("${context.name}")
	private String contextPath;

	@Value("${sessionTimeout}")
	private Integer sessionTimeout;

	@Bean
	public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager,TokenFactory tokenFactory) {
		System.out.println("ShiroConfiguration.shirFilter()");
		ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
		shiroFilterFactoryBean.setSecurityManager(securityManager);

		Map<String, Filter> filtersMap = new LinkedHashMap<String, Filter>();
		/**
		 * statelessAuthcFilter不能拿到外面去会导致anon失效，原因是定义了多个filter与shirofilter 一同被spring-boot 识别,加入了filterChain. 
		 * 相当于statelessAuthcFilter与shiroFilter不再是上下级的关系,而是平级的关系,由spring ApplicationFilterConfig 一起管理了.
		 * 只需要改造一下, 将原来的那些 自定义的Fliter不要在外层Bean定义,直接放到filters的Map内层
		 */
		StatelessAuthcFilter statelessAuthcFilter = new StatelessAuthcFilter();
		statelessAuthcFilter.setTokenFactory(tokenFactory);
		filtersMap.put("statelessAuthc", statelessAuthcFilter);
		shiroFilterFactoryBean.setFilters(filtersMap);
		// 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
		shiroFilterFactoryBean.setLoginUrl("/login");
		// 登录成功后要跳转的链接
		shiroFilterFactoryBean.setSuccessUrl("/index");
		//未授权界面;
		shiroFilterFactoryBean.setUnauthorizedUrl("/403");
		//拦截器.
		Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
		// 配置不会被拦截的链接 顺序判断
		filterChainDefinitionMap.put("/favicon.ico", "anon");
		filterChainDefinitionMap.put("/static/**", "anon");
		filterChainDefinitionMap.put("/login", "anon");
		filterChainDefinitionMap.put("/webLogin", "anon");
		filterChainDefinitionMap.put("/maLogin", "anon");
		filterChainDefinitionMap.put("/webjars/**", "anon");
		filterChainDefinitionMap.put("/webjars/**", "anon");

		filterChainDefinitionMap.put("/swagger-ui.html", "anon");
		filterChainDefinitionMap.put("/v2/api-docs/**", "anon");
		filterChainDefinitionMap.put("/swagger-resources/**", "anon");
		filterChainDefinitionMap.put("/configuration/**", "anon");

		//配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了
		filterChainDefinitionMap.put("/logout", "logout");
		//<!-- 过滤链定义，从上向下顺序执行，一般将/**放在最为下边 -->:这是一个坑呢，一不小心代码就不好使了;
		//<!-- authc:所有url都必须认证通过才可以访问 ,此处用自定义的statelessAuthc; anon:所有url都都可以匿名访问-->
		filterChainDefinitionMap.put("/**", "statelessAuthc");
		shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
		return shiroFilterFactoryBean;
	}


	@Bean
	public MyShiroRealm myShiroRealm(){
		MyShiroRealm myShiroRealm = new MyShiroRealm();
		myShiroRealm.setCachingEnabled(false);
		return myShiroRealm;
	}

	/**
	 * subject工厂管理器.
	 * @return
	 */
	@Bean
	public DefaultWebSubjectFactory subjectFactory(){
		StatelessDefaultSubjectFactory subjectFactory = new StatelessDefaultSubjectFactory();
		return subjectFactory;
	}

	@Bean(name="webTokenProcessor")
	public DefaultTokenPorcessor webTokenProcessor(){
		DefaultTokenPorcessor webT = new DefaultTokenPorcessor();
		webT.setId("web");
		webT.setPath(contextPath);
		webT.setExpr(sessionTimeout);
		List<String> exacts = new ArrayList<String>();
		exacts.add("userType");
		webT.setExacts(exacts);
		return webT;
	}

	@Bean(name="maTokenProcessor")
	public DefaultTokenPorcessor maTokenProcessor(){
		DefaultTokenPorcessor maT = new DefaultTokenPorcessor();
		maT.setId("ma");
		maT.setPath(contextPath);
		maT.setExpr(sessionTimeout);
		List<String> exacts = new ArrayList<String>();
		exacts.add("userType");
		maT.setExacts(exacts);
		return maT;
	}

	@Bean
	public TokenFactory tokenFactory(){
		List<ITokenProcessor> processors = new ArrayList<>();
		processors.add(webTokenProcessor());
		processors.add(maTokenProcessor());
		TokenFactory tokenFactory = new TokenFactory();
		tokenFactory.setProcessors(processors);
		return tokenFactory;
	}

	/**
	 * session管理器：
	 * sessionManager通过sessionValidationSchedulerEnabled禁用掉会话调度器，
	 * 因为我们禁用掉了会话，所以没必要再定期过期会话了。
	 * @return
	 */
	@Bean
	public DefaultSessionManager sessionManager(){
		DefaultSessionManager sessionManager = new DefaultSessionManager();
		sessionManager.setSessionValidationSchedulerEnabled(false);
		return sessionManager;
	}

	@Bean(name="securityManager")
	public SecurityManager securityManager(){
		DefaultWebSecurityManager securityManager =  new DefaultWebSecurityManager();

		securityManager.setRealm(myShiroRealm());
		securityManager.setSubjectFactory(subjectFactory());
		securityManager.setSessionManager(sessionManager());
        /*
         * 禁用使用Sessions 作为存储策略的实现，但它没有完全地禁用Sessions
         * 所以需要配合context.setSessionCreationEnabled(false);
         */
		((DefaultSessionStorageEvaluator)((DefaultSubjectDAO)securityManager.getSubjectDAO()).getSessionStorageEvaluator()).setSessionStorageEnabled(false);
		return securityManager;
	}

	@Bean
	public MethodInvokingFactoryBean methodInvokingFactoryBean(){
		MethodInvokingFactoryBean mfBean = new MethodInvokingFactoryBean();
		mfBean.setStaticMethod("org.apache.shiro.SecurityUtils.setSecurityManager");
		mfBean.setArguments(new Object[]{securityManager() });
		return mfBean;
	}


	@Bean
	public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
		DefaultAdvisorAutoProxyCreator proxyCreator = new DefaultAdvisorAutoProxyCreator();
		proxyCreator.setProxyTargetClass(true);
		return proxyCreator;
	}

	/**
	 *  开启shiro aop注解支持.
	 *  使用代理方式;所以需要开启代码支持;
	 * @param securityManager
	 * @return
	 */
	@Bean
	public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
		AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
		authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
		return authorizationAttributeSourceAdvisor;
	}


}